package com.tanhua.server.service.impl;

import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.CommentDto;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.CommentsService;
import com.tanhua.server.service.UserFreezeService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wjs
 * @version 1.0
 * @date 2021/12/28 0028 下午 2:40
 */

@Service
public class CommentsServiceImpl implements CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private UserFreezeService userFreezeService;

    @Override
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {

        //在comment表中通过publishId(动态id  movementId) , commentType(评论类型，1-点赞，2-评论，3-喜欢)分页查询
        List<Comment> list = commentApi.findPageComments(movementId, CommentType.COMMENT, page, pagesize);

        if (list == null || list.isEmpty()) {
            return new PageResult();
        }

        //获取评论用户id
        List<Long> userIds = list.stream().map(comment -> comment.getUserId()).collect(Collectors.toList());

        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        List<CommentVo> vos = list.stream()
                .filter(comment -> map.get(comment.getUserId()) != null)
                .map(comment -> CommentVo.init(map.get(comment.getUserId()), comment))
                .collect(Collectors.toList());

        return new PageResult(page, pagesize, 0L, vos);
    }

    @Override
    public void saveComments(CommentDto commentDto) {

        //校验用户状态--------------------------
        User user = userApi.findById(UserHolder.getUserId());
        if (user != null) {
            userFreezeService.checkUserStatus(2,user.getId());
        }

        //获取操作用户id
        Long userId = UserHolder.getUserId();
        //2、构造Comment
        Comment comment = new Comment();
        //由CommentApi中save方法向comment对象设置被评论人属性
        comment.setPublishId(new ObjectId(commentDto.getMovementId()));
        comment.setCommentType(CommentType.COMMENT.getType());
        comment.setContent(commentDto.getComment());
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer commentCount = commentApi.save(comment);
    }

    @Override
    public Integer addLike(String commentId) {
        //拼接redis的key，将用户的点赞状态存入redis
        //大键key,小键hashKey,值1(现在还不知道用处,以后可能用到)
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        if (redisTemplate.opsForHash().get(key,hashKey).equals(1)){
            throw new BusinessException(ErrorResult.likeError());
        }

        Comment comment = commentApi.findById(commentId);
        comment.setLikeCount(comment.getLikeCount()+1);
        commentApi.updateById(comment);

        redisTemplate.opsForHash().put(key, hashKey, "1");
        return comment.getLikeCount();
    }
}
